package xyz.yq56.easytool.utils.io;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import xyz.yq56.easytool.utils.collection.MapUtil;
import xyz.yq56.easytool.utils.log.LogUtil;

/**
 * @author yi qiang
 * @date 2021/9/21 13:13
 */
public class IoUtil {

    private IoUtil() {
    }


    /**
     * 从输入流中获取字节数组
     *
     * @param inputStream 输入流
     * @return 字节数组
     * @throws IOException 异常
     */
    public static byte[] readInputStream(InputStream inputStream)
            throws IOException {
        byte[] b = new byte[1024];
        int len;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((len = inputStream.read(b)) != -1) {
            bos.write(b, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }


    /**
     * 输入流转化为字节数组输入流
     *
     * @param inputStream 输入流
     * @return 字节数组输入流
     */
    public static InputStream toByteArrayInputStream(InputStream inputStream) {
        try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            int len;
            byte[] bytes = new byte[1024];
            while ((len = inputStream.read(bytes)) != -1) {
                out.write(bytes, 0, len);
            }
            inputStream.close();
            return new ByteArrayInputStream(bytes);
        } catch (IOException e) {
            LogUtil.warn("toByteArrayInputStream", MapUtil.builder().put("msg", e.getMessage()).maps());
        }
        return null;
    }

}
